<?php
require "../load.php";
error_reporting(0);
$action = $_POST["action"];
unset($_POST["action"]);
if (get_magic_quotes_gpc()) {
    $_POST = Owl_Format::stripslashes_deep($_POST);
}
define('DEFAULT_PAGES_THUMBNAIL', "images/default/pages.png");

switch ($action) {
    case 'add_page' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        $owl_page = new Owl_Page();
        
        //Create file name, or current timestamp
        $now = Owl_Date_Time::current_time('timestamp', true);

        //Do not allow empty content
        if (Owl_Functions::content_is_empty($_POST["page_content"])) {
            echo '<div class="ajax-error">';
            echo __("Page content should not be empty");
            echo '</div>';
            die();
        }

        //Create the nice url
        $nice_url = Owl_Format::make_file_name(trim($_POST["page_title"]));

        //Then check if it has already existed
        if ($owl_page->get_page($nice_url) == true) {
            echo '<div class="ajax-error">';
            echo __("Page title is duplicated");
            echo '</div>';
            die();
        }

        //We will upload the thumb nail first
        $thumbnail_data = $_FILES["page_image_thumb"];
        $data = array();
        
        //First check if user will use the default thumbnail
        if ($thumbnail_data['error'] == 4) {
            $data["image_thumb"] = DEFAULT_PAGES_THUMBNAIL;
        }
        elseif($thumbnail_data['error'] == 0 && is_uploaded_file($thumbnail_data['tmp_name'])) {
            $thumbnail_file_info = pathinfo($thumbnail_data['name']);

            //Check file type
            if (!Owl_Functions::file_upload_is_image($thumbnail_data)) {
                echo '<div class="ajax-error">';
                echo __("Uploaded file is not an image, please upload following file format: JPG, GIF or PNG");
                echo '</div>';
                die();
            }

            $image_thumb_file_name = $now . "." . $thumbnail_file_info["extension"];
            $image_thumb_path = PAGE_PATH . $image_thumb_file_name;
            
            //Move image to pages folder
            if (!@move_uploaded_file($thumbnail_data["tmp_name"], $image_thumb_path)) {
                echo '<div class="ajax-error">';
                echo __("Error while uploading file, your data is not affected by this error.") . "<br />";
                echo sprintf(__("Cannot create file %s in folder %s"), $image_thumb_file_name, SITE_URL . PAGE_DIR);
                echo '</div>';
                die();
            }
            $data["image_thumb"] = DATA_DIR . '/' . PAGE_DIR . "/" . $image_thumb_file_name;
        }
        else {
            echo '<div class="ajax-error">';
            echo __("Error while uploading file, your data is not affected by this error.") . "<br />";
            echo Owl_Functions::get_upload_error($thumbnail_data["error"]);
            echo '</div>';
            die();
        }

        //Clean up HTML
        $page_content = preg_replace('/[\n\t]/i', ' ', $_POST["page_content"]);
        $page_content = preg_replace('/\s{2,}/i', ' ', $page_content);
        $page_content = Owl_Format::force_balance_tags($page_content);

        //Create page content data file
        $page_content_file = $now . ".owl";
        $page_content_path = PAGE_PATH . $page_content_file;
        if (@!Owl_Functions::safe_write_file($page_content_path, $page_content)) {
            echo '<div class="ajax-error">';
            echo __("Error while creating data file, your data is not affected by this error.") . "<br />";
            echo sprintf(__("Cannot create file %s in folder %s"), $page_content_file, SITE_URL . DATA_DIR . "/" . PAGE_DIR);
            echo '</div>';
            die();
        }

        //Create record data
        $data["title"] = Owl_Format::esc_html($_POST["page_title"]);
        $data["create_date"] = $data["modify_date"] = Owl_Date_Time::timestamp_to_xml($now);
        $data["excerpt"] = (Owl_Functions::content_is_empty($_POST["page_excerpt"])) ? htmlspecialchars(Owl_Format::trim_word(strip_tags($page_content), 75)) : htmlspecialchars($_POST["page_excerpt"]);
        $data["nice_url"] = $nice_url;
        $data["content_file"] = $now . ".owl";

        //Create record
        if ($owl_page->insert_pages($data)) {
            echo 1;
        }
        else {
            echo '<div class="ajax-error">';
            echo __("Error while creating data file, your data is not affected by this error.");
            echo $owl_page->get_error();
            echo '</div>';

            //Delete uploaded file
            @unlink($image_thumb_path);
            @unlink($page_content_path);

            die();
        }

        break;
    case 'edit_page' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        $owl_page = new Owl_Page();

        //Create file name, or current timestamp
        $now = Owl_Date_Time::current_time('timestamp', true);

        //Check the existence of page first
        $old_page = $owl_page->get_page($_POST["nice_url"]);
        if (!$old_page) {
            echo '<div class="ajax-error">';
            echo __("Error while updating page") . "<br />";
            echo __("Page does not exist");
            echo '</div>';
            die();
        }
        $data = array();
        $data["modify_date"] = Owl_Date_Time::timestamp_to_xml($now);
        //We will prepare the thumbnail data first
        if ($_POST["use_default_thumb"] == "on") {
            $data["image_thumb"] = DEFAULT_PAGES_THUMBNAIL;
        }
        else {
            $thumbnail_data = $_FILES["page_image_thumb"];

            //If uploading return error, then die
            if ($thumbnail_data["error"] != 0 && $thumbnail_data["error"] != 4) {
                echo '<div class="ajax-error">';
                echo __("Error while uploading file, your data is not affected by this error.") . "<br />";
                echo Owl_Functions::get_upload_error($thumbnail_data["error"]);
                echo '</div>';
                die();
            }
            elseif ($thumbnail_data['error'] == 0 && is_uploaded_file($thumbnail_data['tmp_name'])) {
                $thumbnail_file_info = pathinfo($thumbnail_data['name']);

                //Check file type
                if (!Owl_Functions::file_upload_is_image($thumbnail_data)) {
                    echo '<div class="ajax-error">';
                    echo __("Uploaded file is not an image, please upload following file format: JPG, GIF or PNG");
                    echo '</div>';
                    die();
                }

                $image_thumb_file_name = $now . "." . $thumbnail_file_info["extension"];
                $image_thumb_path = PAGE_PATH . $image_thumb_file_name;
                $data["image_thumb"] = DATA_DIR . '/' . PAGE_DIR . "/" . $image_thumb_file_name;
            }
            else {
                $data["image_thumb"] = $old_page["image_thumb"];
            }
        }

        //Clean up HTML
        $page_content = preg_replace('/[\n\t]/i', ' ', $_POST["page_content"]);
        $page_content = preg_replace('/\s{2,}/i', ' ', $page_content);
        $page_content = Owl_Format::force_balance_tags($page_content);

        //We will update record set
        $data["title"] = Owl_Format::esc_html($_POST["page_title"]);
        $data["excerpt"] = (Owl_Functions::content_is_empty($_POST["page_excerpt"])) ? htmlspecialchars(Owl_Format::trim_word(strip_tags($page_content), 75)) : htmlspecialchars($_POST["page_excerpt"]);
        if (!$owl_page->update_pages($_POST["nice_url"], $data)) {
            echo '<div class="ajax-error">';
            echo __("Error while updating data file, your data is not affected by this error.");
            echo $owl_page->get_error();
            echo '</div>';
            die();
        }
        
        //Delete old image thumb and upload new one
        if ($old_page["image_thumb"] != DEFAULT_PAGES_THUMBNAIL && ($thumbnail_data["error"] == 0 || $_POST["use_default_thumb"] == "on")) {
            if (!@unlink(APS_PATH . $old_page["image_thumb"])) {
                echo '<div class="ajax-error">';
                echo __("Error while updating page: ") . "<br />";
                echo sprintf(__("Cannot delete file %s"), $old_page["image_thumb"]);
                echo '</div>';

                $owl_page->update_pages($_POST["nice_url"], $old_page);
                die();
            }
        }

        if ($_POST["use_default_thumb"] != "on") {
            $image_thumb_path = PAGE_PATH . $image_thumb_file_name;
            @move_uploaded_file($thumbnail_data["tmp_name"], $image_thumb_path);
        }

        //update page content data file
        $page_content_file = $old_page["content_file"];
        $page_content_path = PAGE_PATH . $page_content_file;
        Owl_Functions::safe_write_file($page_content_path, $page_content);
        echo 1;
        break;
    case 'delete_page' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        $owl_page = new Owl_Page();
        
        //Because we will delete and update many file, so checking the writablity first
        $stack_trace = Owl_Stack_Trace::get_instance();
        if (!is_writable(PAGE_PATH)) {
            $stack_trace->raise('delete_page', __("Cannot delete thumbnail and content file"));
        }
        if (!is_writable(DATA_PATH . "pages.xml")) {
            $stack_trace->raise('delete_page', sprintf(__("Can not save file %s"), DATA_PATH . "pages.xml"));
        }
        if ($stack_trace->error_has_been_raised("delete_page")) {
            echo '<div class="ajax-error">';
            echo __("Error while deleting page.");
            $stack_trace->print_error("delete_page");
            echo '</div>';
        }
        else {
            //Get the old page
            $old_page = $owl_page->get_page($_POST["nice_url"]);
            if ($old_page == false) {
                echo '<div class="ajax-error">';
                echo __("Error while deleting page.") . "<br />";
                echo __("Page does not exist");
                echo '</div>';
            }
            else {
                //Now we will delete the record first
                $owl_page->delete_pages($_POST["nice_url"]);

                //Delete thumbnail, if possible
                if ($old_page["image_thumb"] != DEFAULT_PAGES_THUMBNAIL) {
                    if (!@unlink(APS_PATH . $old_page["image_thumb"])) {
                        $stack_trace->raise('delete_page', sprintf(__("Error while deleting thumbnail, please remove the file %s by yourself"), $old_page["image_thumb"]));
                    }
                }

                //Delete content file
                if (!@unlink(PAGE_PATH . $old_page["content_file"])) {
                    $stack_trace->raise('delete_page', sprintf(__("Error while deleting content file, please remove the file %s by yourself"), DATA_DIR . "/" . PAGE_DIR . "/" . $old_page["content_file"]));
                }

                if ($stack_trace->error_has_been_raised('delete_page')) {
                    echo '<div class="ajax-error">';
                    echo __("Error while deleting page.");
                    $stack_trace->print_error("delete_page");
                    echo '</div>';
                }
                else {
                    echo '<div class="ajax-success">';
                    echo __("Delete page successful!");
                    echo '</div>';
                }
            }
        }
        break;
    case 'get_last_page_url' :
        $owl_page = new Owl_Page();
        $last_page_url = $owl_page->get_last_page_url($_POST["type"]);
        echo ($last_page_url) ? $last_page_url : 0;
        break;
    case 'get_last_edit_url' :
        Owl_Link::page_url($_POST["nice_url"]);
        break;
    case 'get_pagination_dropdown' :
        $owl_page = new Owl_Page();
        $owl_page->print_pages_pagination_dropdown();
        break;
    case 'get_pages_table' :
        $owl_page = new Owl_Page();
        $owl_page->print_pages_table($_POST["page"]);
        break;
    default :
        die();
}
